import React, { useEffect, useState, useRef } from "react";
import { Drawer, message, Popconfirm, Tag, Card, Input, Button, Table } from 'antd'
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { DeleteOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons'
import exportExcel from '@/utils/exportExcel';
import XLSX from "xlsx";
import "./index.css"

const isSearch = "scanTerminal"

interface RecordParams {
    devLocation: string,
    hostId: string,
    state: string,
    index: number,
    num: number,
    devType: number,
    createUser: string,
    latitude: number,
    longitude: number,
}

const tiitle = "设备列表"

// 终端管理 -- 扫码设备管路
function Index() {
    const input = useRef<any>('')
    const [addVisible, setAddVisible] = useState(false);
    const [importTable, setImportTable] = useState<any[]>([]) // 导入的导入的TABLE
    const [importTables, setImportTables] = useState<any[]>([]) // 导入的导入的TABLE
    const [upData, setUpData] = useState<boolean>(true)
    const [loadings, setLoadings] = useState<boolean[]>([false, false]);

    const onClose = () => {
        setAddVisible(false);
        setImportTable([])
        setImportTables([])
    };

    const ButClick = () => {
        setAddVisible(true);
    }

    // 批量换卡表格头
    const whiteCardTable: any[] = [
        {
            title: 'imei号',
            dataIndex: 'imei',
            key: 'imei',
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
        },
        {
            title: '旧白卡号',
            dataIndex: 'oldWhiteCard',
            key: 'oldWhiteCard',
        },
        {
            title: '新白卡号',
            dataIndex: 'newWhiteCard',
            key: 'newWhiteCard',
        },
        {
            title: '错误提示',
            render: (record: any) => {
                return <span style={{ color: record.error == "1" ? '#ff4d4f' : '#d9d9d9' }}>{record.error == "1" ? "信息不能为空" : ""}</span>
            }
        }
    ]

    // 批量换卡表格头
    const whiteCardTables: any[] = [
        {
            title: 'imei号',
            dataIndex: 'imei',
            key: 'imei',
        },
        {
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
        },
        {
            title: '旧白卡号',
            dataIndex: 'oldWhiteCard',
            key: 'oldWhiteCard',
        },
        {
            title: '新白卡号',
            dataIndex: 'newWhiteCard',
            key: 'newWhiteCard',
        },
        {
            title: '错误提示',
            render: (record: any) => {
                return <span style={{ color: !record.isReplace ? '#ff4d4f' : '#11e516' }}>{record.remark}</span>
            }
        }
    ]

    // 上传白卡号文件
    const fileChange = async (e: any) => {
        // console.log(e);
        
        setImportTable([])
        setImportTables([])
        const file = e.target.files?.[0]
        setUpData(false)
        if (file) {
            const list = await handleExcelFile<any[]>(file)
            const tempList = list.map(item => ({
                imei: item['imei号'],
                studentId: item['学号'],
                oldWhiteCard: item['旧白卡号'],
                newWhiteCard: item['新白卡号'],
                rowNum: item.__rowNum__,
            }))
            tempList.forEach((item: any) => {
                for (const key in item) {
                    if (!item[key]) {
                        setUpData(true)
                        item.error = 1
                    } else {
                    }
                }
            })
            setImportTable(tempList)
        }
    }


    const handleExcelFile = <T,>(file: File) => {
        let reader = new FileReader();  // 使用 FileReader 读取数据

        return new Promise<T>(((resolve, reject) => {

            reader.onload = function (e) {  // 数据读取完成后的回调函数
                try {

                    let workbook = XLSX.read(e.target?.result, { type: 'binary' })
                    let firstSheetName = workbook.SheetNames[0];  // 获取第一个 sheet 的名字
                    let worksheet = workbook.Sheets[firstSheetName];  // 获取第一个 sheet 的内容
                    let res = XLSX.utils.sheet_to_json(worksheet) as unknown as T;  // 使用 utils 里的方法转换内容为便于使用的数组
                    resolve(res)
                } catch (e) {
                    message.error("数据异常！");
                    reject(e)
                }
            };
            reader.readAsBinaryString(file);  // 读取数据

        }))
    }

    //  发送请求 拿到表格数据
    const getAbnormal = async (params: any) => {
        setLoadings([true, false])
        try {
            const json = await fetchRequest(url.CET_CONSUMEREPLACEWHITECARD, params);
            if (json.success) {
                setImportTables(json.data)
                setLoadings([false, false])
            } else {
                setLoadings([false, false])
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            setLoadings([false, false])
            message.error(error.message)
        }
    }


    // 发送表格数据请求传参
    const getTableDatas = useRequest(getAbnormal, {
        manual: true,
        loadingDelay: 200
    })
    const importClick = () => {
        console.log(upData);
        
        !upData ? getTableDatas.run(importTable) : message.error("请上传正确白卡数据");

    }
    const leadingOut = async () => {
        setLoadings([false, true])
        if (importTables.length > 0) {
            const data = importTables.map((item: any) => {
                const tempItem = {}
                tempItem['imei号'] = item.imei
                tempItem['学号'] = item.studentId
                tempItem['旧白卡号'] = item?.oldWhiteCard
                tempItem['新白卡号'] = item.newWhiteCard
                tempItem['错误提示'] = item.remark
                tempItem['上传结果'] = item.isReplace ? '成功' : '失败'
                return tempItem
            })
            exportExcel(data, '白卡批量换卡模板.xlsx')
            setLoadings([false, false])
        } else message.error("请上传白卡数据在导出")
        setLoadings([false, false])
    }
    const [tableData, setTableData] = useState<any[]>()
    let arrList:any[] =[]
    const getSearchImei = async (params:any) =>{
        try {
            const json = await fetchRequest(url.CET_STUDENTINFOBYIMEI, params);
            if (json.success) {
               
                arrList.push(json.data)
                setTableData([json.data])
                
            } else {
                message.error(json.errorMsg)
            }
        } catch (error: any) {
            message.error(error.message)
        }
       
    }
    const getTableData = useRequest(getSearchImei, {
        manual: true,
        loadingDelay: 200
    })
   
    const SearchImei = () =>{
        getTableData.run({imei:input.current.input.value})
        
    }

    return (
        <div className="eenew-form">
            <Card className="search-box" style={{ padding: 24 }}>
                <span>imei卡号：</span>
                <Input style={{ width: 300, marginRight: '10px' }} ref={input} />
                <Button type={'primary'} className={'search-form-btn'} icon={<SearchOutlined />} style={{ marginRight: '10px' }} onClick={() => {
                    if (!input.current!.input.value) {
                        message.error('请输入imei卡号')
                        return
                    }
                    SearchImei()
                }}>搜索</Button>
                <Button onClick={() => ButClick()}>批量换卡</Button>
            </Card>
            <Drawer width="60%" title="批量换卡" visible={addVisible} onClose={onClose} destroyOnClose>
                <div>
                    导入模板: <span className={'import-val'}><a href={require('@/excel/白卡批量换卡模板.xlsx')} download>模板下载</a></span>
                </div>
                <div>
                    上传文件: <span className={'import-val'}>
                        <input type='file' accept='.xlsx, .xls'
                            onChange={(e) => fileChange(e)} ref={input} />
                    </span>
                </div>
                <div>
                    数据预览：
                </div>
                <div>
                    <Table columns={whiteCardTable} rowKey={(record: any) => record.rowNum}
                        pagination={{ hideOnSinglePage: true, simple: true, pageSize: 4, }}
                        dataSource={importTable}
                    />
                </div>
                <div style={{ paddingBottom: 5 }}>
                    <Button type="primary" onClick={importClick} loading={loadings[0]} htmlType="submit">提交</Button>
                    <Button style={{ marginLeft: 20 }} type="primary" onClick={leadingOut} loading={loadings[1]} htmlType="submit">导出</Button>
                </div>
                <div>
                    错误提示:
                </div>
                <div>
                    <Table columns={whiteCardTables} rowKey={(record: any) => record.newWhiteCard}
                        pagination={{ hideOnSinglePage: true, simple: true, pageSize: 4, }}
                        dataSource={importTables}
                    />
                </div>
            </Drawer>
            <ATable  tableData={tableData}/>
        </div>
    );
}
const ATable = (props:any) => {
    const { tableData } = props
    const columns: any[] = [

        {
            title: '学生姓名',
            dataIndex: 'studentName',
            key: 'studentName',
        },
        {
            title: 'imei卡号',
            dataIndex: 'imei',
            key: 'imei',
        },
        { 
            title: '学号',
            dataIndex: 'studentId',
            key: 'studentId',
        },
        {
            title: '白卡号',
            dataIndex: 'whiteCard',
            key: 'whiteCard;',
        },
    ]
  
    return <>

        <Table className={'table-forms'} columns={columns} rowKey={(record: any) => record.imei} dataSource={tableData} />
    </>
}
export default Index
